<template>
  <div v-if="visible" class="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4">
    <div class="bg-white rounded-lg shadow-lg w-full max-w-md max-h-[90vh] flex flex-col">
      <!-- 弹窗头部 -->
      <div class="flex items-center justify-between px-6 py-4 border-b border-gray-200">
        <h3 class="text-lg font-semibold text-gray-800">编辑文件信息</h3>
        <button @click="handleClose" class="text-gray-500 hover:text-gray-700">
          <i class="fa fa-times"></i>
        </button>
      </div>
      
      <!-- 弹窗内容 -->
      <div class="flex-1 px-6 py-4 overflow-y-auto">
        <div v-if="file" class="space-y-4">
          <!-- 文件预览缩略图 -->
          <div v-if="file.type === 'image' && file.url" class="text-center">
            <img
              :src="file.url"
              alt="文件预览"
              class="max-w-full h-32 object-contain mx-auto rounded-md"
            >
          </div>
          
          <!-- 文件图标 -->
          <div v-else class="text-center py-4">
            <i class="fa" :class="getFileIconClass()" style="font-size: 4rem;"></i>
          </div>
          
          <!-- 表单字段 -->
          <div class="space-y-4">
            <!-- 文件名 -->
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">文件名</label>
              <input
                v-model="formData.name"
                type="text"
                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
                placeholder="请输入文件名"
              >
            </div>
            
            <!-- 文件分类 -->
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">文件分类</label>
              <select v-model="formData.category" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent">
                <option value="banner">轮播图</option>
                <option value="product">产品图片</option>
                <option value="article">文章配图</option>
                <option value="avatar">头像</option>
                <option value="other">其他</option>
              </select>
            </div>
            
            <!-- 文件说明 -->
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">文件说明</label>
              <textarea
                v-model="formData.description"
                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
                rows="3"
                placeholder="请输入文件说明（可选）"
              ></textarea>
            </div>
            
            <!-- 文件信息（只读） -->
            <div class="border-t border-gray-200 pt-4">
              <div class="text-sm text-gray-500 mb-2">文件信息</div>
              <div class="grid grid-cols-2 gap-2 text-sm">
                <div class="text-gray-600">文件类型：</div>
                <div>{{ getFileTypeText() }}</div>
                <div class="text-gray-600">文件大小：</div>
                <div>{{ formatFileSize(file.size * 1024) }}</div>
                <div class="text-gray-600">上传时间：</div>
                <div>{{ formatDate(file.uploadTime) }}</div>
                <div class="text-gray-600">上传人：</div>
                <div>{{ file.uploadBy || 'admin' }}</div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 无文件信息 -->
        <div v-else class="flex items-center justify-center h-40 text-gray-500">
          暂无文件信息
        </div>
      </div>
      
      <!-- 弹窗底部 -->
      <div class="px-6 py-4 border-t border-gray-200 flex justify-end space-x-3">
        <button
          @click="handleClose"
          class="px-4 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50 transition-colors"
          :disabled="saving"
        >
          取消
        </button>
        <button
          @click="handleSave"
          class="px-4 py-2 bg-indigo-600 text-white rounded-md hover:bg-indigo-700 transition-colors"
          :disabled="!file || saving"
        >
          <i v-if="saving" class="fa fa-spinner fa-spin mr-1"></i>
          {{ saving ? '保存中...' : '保存' }}
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, watch, computed } from 'vue'
import { useValidator } from '@/composables/useValidator'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  file: {
    type: Object,
    default: null
  }
})

const emit = defineEmits(['close', 'save'])

// 使用验证器
const { validateField } = useValidator()

// 状态管理
const saving = ref(false)
const formData = reactive({
  name: '',
  category: 'other',
  description: ''
})

// 监听文件变化，更新表单数据
watch(() => props.file, (newFile) => {
  if (newFile && props.visible) {
    // 复制文件数据到表单
    formData.name = newFile.name || ''
    formData.category = newFile.category || 'other'
    formData.description = newFile.description || ''
  }
}, { immediate: true })

// 处理保存
const handleSave = async () => {
  if (!props.file) return
  
  // 验证表单
  if (!formData.name.trim()) {
    alert('请输入文件名')
    return
  }
  
  saving.value = true
  
  try {
    // 模拟保存过程
    await new Promise(resolve => setTimeout(resolve, 800))
    
    // 创建更新后的文件数据
    const updatedFile = {
      ...props.file,
      name: formData.name.trim(),
      category: formData.category,
      description: formData.description.trim()
    }
    
    // 触发保存事件
    emit('save', updatedFile)
    
    // 关闭弹窗
    handleClose()
  } catch (error) {
    console.error('保存失败:', error)
    alert('保存失败，请重试')
  } finally {
    saving.value = false
  }
}

// 处理关闭
const handleClose = () => {
  if (!saving) {
    emit('close')
  }
}

// 获取文件图标类名
const getFileIconClass = () => {
  if (!props.file) return ''
  
  if (props.file.type === 'image') return 'fa-file-image-o text-green-500'
  if (props.file.type === 'video') return 'fa-file-video-o text-blue-500'
  if (props.file.type === 'document') {
    const name = props.file.name.toLowerCase()
    if (name.endsWith('.pdf')) return 'fa-file-pdf-o text-red-500'
    if (name.endsWith('.doc') || name.endsWith('.docx')) return 'fa-file-word-o text-blue-400'
    if (name.endsWith('.xls') || name.endsWith('.xlsx')) return 'fa-file-excel-o text-green-400'
    return 'fa-file-text-o text-gray-500'
  }
  
  return 'fa-file-o text-gray-500'
}

// 获取文件类型文本
const getFileTypeText = () => {
  if (!props.file) return ''
  
  const typeMap = {
    'image': '图片',
    'video': '视频',
    'document': '文档'
  }
  
  return typeMap[props.file.type] || props.file.type
}

// 格式化文件大小
const formatFileSize = (sizeBytes) => {
  if (sizeBytes >= 1024 * 1024) {
    return (sizeBytes / (1024 * 1024)).toFixed(2) + ' MB'
  } else if (sizeBytes >= 1024) {
    return (sizeBytes / 1024).toFixed(2) + ' KB'
  }
  return sizeBytes + ' B'
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}
</script>

<style scoped>
/* 表单动画 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.fade-in {
  animation: fadeIn 0.3s ease;
}

/* 输入框焦点样式 */
input:focus,
textarea:focus,
select:focus {
  transition: all 0.2s ease;
}

/* 保存按钮动画 */
button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}
</style>